#!/usr/bin/env python3
"""
测试Web界面的大视频分析功能
"""

import requests
import json
from pathlib import Path

def test_large_analysis():
    """测试大视频分析API"""
    
    # 服务器地址
    base_url = "http://192.168.210.72:8000"
    
    # 检查服务器状态
    try:
        response = requests.get(f"{base_url}/")
        print(f"✅ 服务器运行正常，状态码: {response.status_code}")
    except Exception as e:
        print(f"❌ 服务器连接失败: {e}")
        return
    
    # 查找测试视频文件
    uploads_dir = Path("uploads")
    video_files = list(uploads_dir.glob("*.mp4"))
    
    if not video_files:
        print("❌ 没有找到测试视频文件")
        return
    
    test_video = video_files[0]
    print(f"📹 使用测试视频: {test_video.name}")
    
    # 准备测试数据
    files = {
        'file': (test_video.name, open(test_video, 'rb'), 'video/mp4')
    }
    
    data = {
        'prompt': '请简单描述这个视频的内容',
        'split_method': 'duration',
        'segment_duration': '60',
        'max_segments': '3',
        'analysis_mode': 'sequential',
        'min_segment_duration': '10'
    }
    
    try:
        print("🚀 开始大视频分析...")
        response = requests.post(
            f"{base_url}/api/analyze-large",
            files=files,
            data=data,
            timeout=300  # 5分钟超时
        )
        
        files['file'][1].close()  # 关闭文件
        
        if response.status_code == 200:
            result = response.json()
            
            if result.get('success'):
                analysis_result = result.get('result', {})
                
                print("✅ 大视频分析成功!")
                print(f"📊 结果类型: {analysis_result.get('type', 'unknown')}")
                print(f"📊 片段数量: {analysis_result.get('segment_count', 0)}")
                print(f"📊 成功分析: {analysis_result.get('successful_segments', 0)}")
                print(f"📊 失败片段: {analysis_result.get('failed_segments', 0)}")
                print(f"📊 分析方法: {analysis_result.get('split_method', 'unknown')}")
                print(f"📊 总时长: {analysis_result.get('total_duration', 0):.1f}s")
                
                # 检查整体摘要
                if analysis_result.get('overall_summary'):
                    summary = analysis_result['overall_summary']
                    print(f"📝 整体摘要长度: {len(summary)} 字符")
                    print(f"📝 摘要预览: {summary[:100]}...")
                else:
                    print("⚠️  没有整体摘要")
                
                # 检查关键洞察
                if analysis_result.get('key_insights'):
                    insights = analysis_result['key_insights']
                    print(f"🔍 关键洞察: {len(insights)} 项")
                    for key, value in insights.items():
                        if isinstance(value, list) and value:
                            print(f"   - {key}: {value[0]}")
                else:
                    print("⚠️  没有关键洞察")
                
                # 检查详细结果
                detailed_results = analysis_result.get('detailed_results', [])
                print(f"📋 详细结果: {len(detailed_results)} 个片段")
                
                for i, segment_result in enumerate(detailed_results):
                    status = segment_result.get('status', 'unknown')
                    segment_info = segment_result.get('segment_info', {})
                    filename = segment_info.get('filename', 'unknown')
                    print(f"   片段 {i+1}: {filename} - {status}")
                
                return True
                
            else:
                print(f"❌ 分析失败: {result.get('message', '未知错误')}")
                return False
        else:
            print(f"❌ HTTP错误: {response.status_code}")
            print(f"响应内容: {response.text}")
            return False
            
    except requests.exceptions.Timeout:
        print("❌ 请求超时")
        return False
    except Exception as e:
        print(f"❌ 请求异常: {e}")
        return False

if __name__ == "__main__":
    print("🧪 测试Web界面大视频分析功能")
    print("=" * 50)
    
    success = test_large_analysis()
    
    print("=" * 50)
    if success:
        print("✅ 测试完成，功能正常")
    else:
        print("❌ 测试失败，需要检查问题")